//MountManager - the program for easy mounting of storage devices in Linux
//Copyright (C) 2007-2008 Tikhonov Sergey
//
//This file is part of MountManager Gui
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#include <QtCore/QSettings>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QComboBox>
#include <QtGui/QLabel>
#include <QtGui/QTextBrowser>
#include <QtGui/QLineEdit>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QSplitter>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include "restorationsystem.h"
#include "const.h"
#include "../core/diskcore.h"

RestorationSystem::RestorationSystem(DiskCore *diskCore,QWidget *parent) : QDialog(parent) {
	core = diskCore;
		
	listWidget = new QListWidget;
	comboBox = new QComboBox;
	comboBox->addItem(tr("List"),"list");
	comboBox->addItem(tr("Native"),"native");
	textBrowser = new QTextBrowser;
	filter = new QLineEdit;
	splitter = new QSplitter;
	
	removeButton = new QPushButton(tr("Remove"));
	removeButton->setEnabled(false);

	backupButton = new QPushButton(tr("Restore"));
	backupButton->setEnabled(false);

	foreach (BackUp *backup,core->backups())
		addBackup(backup);
		
	QHBoxLayout *bottomLayout = new QHBoxLayout;
	bottomLayout->addStretch();
	bottomLayout->addWidget(backupButton);
	
	QHBoxLayout *filterLayout = new QHBoxLayout;
	filterLayout->addWidget(new QLabel(tr("Filter") + ":"));
	filterLayout->addWidget(filter);
	filterLayout->addStretch();
	filterLayout->addWidget(removeButton);
	
	QHBoxLayout *comboBoxLayout = new QHBoxLayout;
	comboBoxLayout->addWidget(new QLabel(tr("View of configuration text") + ":"));
	comboBoxLayout->addWidget(comboBox);
	comboBoxLayout->addStretch();
	
	QVBoxLayout *leftLayout = new QVBoxLayout;
	leftLayout->addWidget(new QLabel("<b>" + tr("Date of change") + ":"));
	leftLayout->addWidget(listWidget);
	leftLayout->addLayout(filterLayout);
	
	QVBoxLayout *rightLayout = new QVBoxLayout;
	rightLayout->addWidget(new QLabel("<b>" + tr("Last configuration file content") + "</b>:" ));
	rightLayout->addLayout(comboBoxLayout);
	rightLayout->addWidget(textBrowser);
	
	QWidget *leftWidget = new QWidget;
	leftWidget->setLayout(leftLayout);
	
	QWidget *rightWidget = new QWidget;
	rightWidget->setLayout(rightLayout);
	
	splitter->addWidget(leftWidget);
	splitter->addWidget(rightWidget);
	splitter->setStretchFactor(1,1);
	splitter->setCollapsible(0,false);
	splitter->setCollapsible(1,false);
	
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(splitter);
	mainLayout->addLayout(bottomLayout);
	setLayout(mainLayout);
	setWindowTitle(tr("Restoration system"));
	resize(600,300);

	updateTextBrowser();
	connect(listWidget,SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)),this,SLOT(updateTextBrowser()));
	connect(comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(updateTextBrowser()));
	connect(filter,SIGNAL(textChanged(const QString&)),this,SLOT(setFilter(const QString&)));
	connect(removeButton,SIGNAL(clicked()),this,SLOT(remove()));
	connect(backupButton,SIGNAL(clicked()),this,SLOT(restore()));
}

RestorationSystem::~RestorationSystem() {
	delete removeButton;
	delete listWidget;
	delete comboBox;
	delete textBrowser;
	delete filter;
	delete splitter;
}

void RestorationSystem::addBackup(BackUp *backup) {
	QListWidgetItem *newItem = new QListWidgetItem;
	newItem->setData(Qt::UserRole,core->backups().indexOf(backup));
	newItem->setText(backup->time + " " + backup->date);
	listWidget->addItem(newItem);
	if (listWidget->count() == 1)
		listWidget->setCurrentItem(newItem);
	
}

void RestorationSystem::addBackup(const QString& backupText) {
	BackUp *backup = core->createBackUp(backupText);
	addBackup(backup);
}

void RestorationSystem::updateTextBrowser(QListWidgetItem *item) {
	if (!item)
		item = listWidget->currentItem();
	if (!item) {
		removeButton->setEnabled(false);
		return;
	}
	removeButton->setEnabled(true);
	backupButton->setEnabled(true);
	BackUp *backup = core->backUp(item->data(Qt::UserRole).toInt());
	if (!backup)
		return;
	if (comboBox->itemData(comboBox->currentIndex()).toString() == "native")
		textBrowser->setText(backup->content);
	else {
		QString currentText;
		foreach (QString line, backup->content.split("\n")) {
			if (line.isEmpty())
				continue;
			if (line.contains("#"))
				continue;
			line.replace("\t"," ");
			QStringList list = line.split(" ");
			list.removeAll(" ");
			if (list.count() != 6)
				continue;
			if (list[1].isEmpty())
				list[1] = "<font color='red'>Unknown</font>";
			currentText += tr("Device") + ": <b>" + list[0] +"</b><br>"
					+ tr("Mount point") + ": <b>" + list[1] + "</b><br>"
					+ tr("File system") + ": <b>" + list[2] + "</b><br>"
					+ tr("Options") + ": <b>" + list[3] + "</b><br>"
					+ tr("Dump flag") + ": <b>" + list[4] + "</b><br>"
					+ tr("Fsck value") + ": <b>" + list[5] + "</b><hr>";
		}
		textBrowser->setHtml(currentText);
	}
}

void RestorationSystem::saveSettings() {
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	settings.setValue("RestorationSystem/State",splitter->saveState());
}

void RestorationSystem::loadSettings() {
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	splitter->restoreState(settings.value("RestorationSystem/State").toByteArray());
}

void RestorationSystem::setFilter(const QString& filterText) {
	if (filterText.isEmpty()) {
		for (int i = 0; i < listWidget->count(); i++)
			listWidget->item(i)->setHidden(false);
		return;
	}
	for (int i = 0; i < listWidget->count(); i++)
		listWidget->item(i)->setHidden(true);
	foreach (QListWidgetItem *item,listWidget->findItems(filterText,Qt::MatchContains))
		item->setHidden(false);
}

void RestorationSystem::remove() {
	QListWidgetItem *item = listWidget->currentItem();
	if (!item)
		return;
	core->removeBackUp(core->backUp(item->data(Qt::UserRole).toInt()));
	delete item;
	if (listWidget->count() > 0) {
		listWidget->setCurrentRow(0);
		updateTextBrowser();
	} else {
		textBrowser->clear();
		backupButton->setEnabled(false);
		removeButton->setEnabled(false);
	}
}

void RestorationSystem::restore() {
	QListWidgetItem *item = listWidget->currentItem();
	if (item == 0) {
		backupButton->setEnabled(false);
		return;
	}
	if (core->setFstabContent(core->backUp(item->data(Qt::UserRole).toInt())->content) == 0) {
		QMessageBox::warning(this,tr("Attention"),tr("You have to start the program again, because the program needs to update information from new content of configuration file."));
		qApp->quit();
	} else
		QMessageBox::warning(this,tr("Error"),tr("Cannot replace main configuration file, for there are no rights for it. Start the program with root privileges."));
}
